#define  _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>

struct student
{
	char name[20];
	int age;
};


void Swap(char* p1, char* p2,size_t width)
{
	for (int i = 0; i < width; i++)
	{
		char tmp = *p1;
		*p1 = *p2;
		*p2 = tmp;

		p1++;
		p2++;
	}

}

int cmp1(const void* p1, const void* p2)
{
	return *(int*)p1 - *(int*)p2;
}

int cmp_by_age(const void* p1, const void* p2)
{
	return ((struct student*)p1)->age - ((struct student*)p2)->age;
}

int cmp_by_name(const void* p1, const void* p2)
{
	return strcmp(((struct student*)p1)->name,((struct student*)p2)->name);
}

void qsort(void* arr, size_t num, size_t width, int(*cmp)(void*, void*))
{
	int i = 0;
	int j = 0;
	for (i = 0; i < num - 1; i++)
	{
		for (j = 0; j <num - 1 - i; j++)
		{
			if (cmp((char*)arr + j * width, (char*)arr + (j + 1) * width, width) > 0)
			{
				Swap((char*)arr + j * width,(char*) arr + (j + 1) * width, width);
			}
		}
	}
}


void test1()
{
	int arr[] = { 15,54,544,58,213,3216,34,135,1354,5442 };
	int num = sizeof(arr) / sizeof(arr[0]);
	qsort(arr, num, sizeof(arr[0]), cmp1);
	for (int i = 0; i < num; i++)
	{
		printf("%d\n", arr[i]);
	}
}

void test2()
{
	struct student arr[] = { {"zhangsan",20},{"lisi",50},{"wangwu",35} };
	int num = sizeof(arr) / sizeof(arr[0]);
	qsort(arr, num, sizeof(arr[0]), cmp_by_age);
	for (int i = 0; i < num; i++)
	{
		printf("%s  %d\n", arr[i].name, arr[i].age);
	}
}

void test3()
{
	struct student arr[] = { {"zhangsan",20},{"lisi",25},{"wangwu",35} };
	int num = sizeof(arr) / sizeof(arr[0]);
	qsort(arr, num, sizeof(arr[0]), cmp_by_name);
	for (int i = 0; i < num; i++)
	{
		printf("%s  %d\n", arr[i].name, arr[i].age);
	}
}

int main()
{
	//test1();
	//test2();
	test3();

	return 0;
}